#include "myfile.h"
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <string.h>

#define FILE_POW 0666

_FILE* _fopen(const char* filename, const char* flag)
{
    assert(filename);
    assert(flag);

    int fd = -1;
    int f = 0;
    if (strcmp(flag, "w") == 0)
    {
        f = O_WRONLY|O_CREAT|O_TRUNC; 
        fd = open(filename, f, FILE_POW);
    }
    else if (strcmp(flag, "a") == 0)
    {
        f = O_WRONLY|O_CREAT|O_APPEND;
        fd = open(filename, f, FILE_POW);
    }
    else if (strcmp(flag, "r") == 0)
    {
        f = O_RDONLY;
        fd = open(filename, f);
    }
    else
    {
        return NULL;
    }

    if (fd == -1)
    {
        return NULL;
    }

    _FILE* _file = (_FILE*)malloc(sizeof(_FILE));
    _file->fileno = fd;
    _file->flush_flag = FLUSH_COLUM;
    _file->put_pos = 0;

    return _file;
}

int _fwrite(_FILE* fp, const char* str, int len)
{
    memcpy(&fp->inbuffer[fp->put_pos], str, len);
    fp->put_pos += len;

    if (fp->flush_flag & FLUSH_NOW)
    {
        write(fp->fileno, fp->inbuffer, fp->put_pos);
        fp->put_pos = 0;
    }
    else if (fp->flush_flag & FLUSH_COLUM)
    {
        if (fp->inbuffer[fp->put_pos-1] == '\n')
        {
            write(fp->fileno, fp->inbuffer, fp->put_pos);
            fp->put_pos = 0;
        }
    }
    else if (fp->flush_flag & FLUSH_ALL)
    {
        if (fp->put_pos == SIZE)
        {
            write(fp->fileno, fp->inbuffer, fp->put_pos);
            fp->put_pos = 0;
        }
    }
    return len;
}

void _fflush(_FILE* fp)
{
    if (fp->put_pos > 0)
    {
        write(fp->fileno, fp->inbuffer, fp->put_pos);
        fp->put_pos = 0;
    }
}

void _fclose(_FILE* fp)
{
    if (fp == NULL)
    {
        return;
    }
    _fflush(fp);
    close(fp->fileno);
    free(fp);
}
